import sys
sys.path.append("../")
from neo4j.v1 import GraphDatabase
from settings import NEO4J_CONFIG, LABEL_STRUCTURE

def create_label_node_and_rel():
    '''
    该函数用于创建标签的节点和边
    :return:
    '''
    _driver = GraphDatabase.driver(**NEO4J_CONFIG)
    with _driver.session() as session:
        cypher = "MATCH(a:Label) DETACH DELETE a"
        session.run(cypher)
        def _create_node_rel(l:dict):
            if not l: return
            for k, v in l.items():
                cypher = "MERGE(a:Label{title: %r})" % (k)
                session.run(cypher)
                def __c(word):
                    cypher = "CREATE(a:Label{title: %r}) SET a.name=%r WITH a MATCH(b:Label{title: %r}) MERGE(b)-[r:Contain]-(a)" %(
                        word, word, k)
                    session.run(cypher)
                list(map(__c, v))
        list(map(_create_node_rel, LABEL_STRUCTURE))

import os
import random
import fileinput
csv_path = "./labels"
def create_vocabulary_node_and_rel():
    _driver = GraphDatabase.driver(**NEO4J_CONFIG)
    with _driver.session() as session:
        cypher = "MATCH(a:Vocabulary) DETACH DELETE a"
        session.run(cypher)
        def _create_v_and_r(csv):
            path = os.path.join(csv_path, csv)
            word_list = list(set(map(lambda x: x.strip(), fileinput.FileInput(path))))
            def __create_node(word):
                weight = round(random.uniform(0.5, 1), 3)
                cypher = "CREATE(a:Vocabulary{name:%r}) WITH a MATCH(b:Label{title:%r}) MERGE(a)-[r:Related{weight:%f}]-(b)" %(word, csv[:-4], weight)
                session.run(cypher)
            list(map(__create_node, word_list))
        label_list = os.listdir(csv_path)
        list(map(_create_v_and_r, label_list))

if __name__ == '__main__':
    #create_label_node_and_rel()
    create_vocabulary_node_and_rel()
